//
//  PhotoEditorViewController.m
//  Logistics
//
//  Created by 刘峰 on 2017/12/12.
//  Copyright © 2017年 com.Logistics. All rights reserved.
//

#import "PhotoEditorViewController.h"
#import "SinglePictureViewCell.h"
#import "PhotoBrowerManager.h"

@interface PhotoEditorViewController () <UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>

{
    BOOL selected;
}
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topHeightLayout;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomHeightLayout;

@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet UIView *topView;
@property (weak, nonatomic) IBOutlet UIView *bottomView;

@property (nonatomic, strong) NSMutableDictionary *imageDictionary;

@end


@implementation PhotoEditorViewController

static NSString * const reuseIdentifier = @"SinglePictureViewCell";

- (IBAction)getBack:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    if (IS_IPHONEX) {
        _topHeightLayout.constant    = 88;
        _bottomHeightLayout.constant = 50 + 34;
    }
    
    if (@available(iOS 11.0, *)) {
        self.collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }

    [self.collectionView registerNib:[UINib nibWithNibName:@"SinglePictureViewCell" bundle:nil] forCellWithReuseIdentifier:reuseIdentifier];
}

- (IBAction)choosePictureOrRemoveAction:(id)sender {
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark <UICollectionViewDataSource, UICollectionViewDelegate>
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.assetList.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    SinglePictureViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    
    if (!cell.selectBtn.hidden) {
        cell.singleImage.backgroundColor = [UIColor blackColor];
        cell.singleImage.contentMode = UIViewContentModeScaleAspectFit;
        cell.selectBtn.hidden = YES;
    }
    [cell photoAsset:self.assetList[indexPath.item] Original:YES imageOption:self.imageDictionary];
    
    return cell;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(KscreenWidth, KscreenHeight);
}

-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}


-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    selected = !selected;
    
    CGFloat topY = 0, bottomY = KscreenHeight-_bottomHeightLayout.constant;
    if (selected) {
        topY    = -_topHeightLayout.constant;
        bottomY = KscreenHeight;
    }else {
        _topView.hidden    = NO;
        _bottomView.hidden = NO;
    }
    
    [UIView animateWithDuration:.4 animations:^{
        _topView.y    = topY;
        _bottomView.y = bottomY;
    } completion:^(BOOL finished) {
        if (selected) {
            _topView.hidden    = YES;
            _bottomView.hidden = YES;
        }
    }];
    
}

/*
#pragma Mark - - -  SinglePictureViewCellDelegate（移出图片 回到上一级）  -- -
-(void)moveOutPictureAction:(UIPanGestureRecognizer *)sender {
    //得到当前手势所在视图
    UIView *view = sender.view;
    //得到我们在视图上移动的偏移量
    CGPoint currentPoint = [sender translationInView:self.view];
    //通过2D仿射变换函数中与位移有关的函数实现视图位置变化
    view.transform = CGAffineTransformTranslate(view.transform, currentPoint.x, currentPoint.y);
    
    NSLog(@"point = %@\n",NSStringFromCGPoint(currentPoint));
    //复原 // 每次都是从00点开始
    [sender setTranslation:CGPointZero inView:view.superview];
}
 */


- (IBAction)editCurrentPicture:(id)sender {
    
}


- (IBAction)useTheseImages:(UIButton *)sender {
    sender.enabled = NO;

    [(PHCachingImageManager *)[PHCachingImageManager defaultManager] stopCachingImagesForAllAssets];
    [GRHUD showProgress:@"正在处理" atView:self.view];
    for (PHAsset *asset in self.assetList) {
        
        if (self.imageDictionary.allKeys.count == self.assetList.count) {
            [GRHUD dismissHUD:self.view];
            [[NSNotificationCenter defaultCenter] postNotificationName:KNotificationDidFinishIMAGE object:self userInfo:@{@"images":self.imageDictionary.allValues}];
            [self dismissALLViewController];
            
        }else {
            if (![self.imageDictionary.allKeys containsObject:asset.localIdentifier]) {
                WEAKSELF
                [asset getOriginalImageLoadedBlock:^(UIImage *image) {
                    [weakSelf.imageDictionary setValue:image forKey:asset.localIdentifier];
                    if (weakSelf.imageDictionary.allKeys.count == weakSelf.assetList.count) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [GRHUD dismissHUD:weakSelf.view];

                            [[NSNotificationCenter defaultCenter] postNotificationName:KNotificationDidFinishIMAGE object:weakSelf userInfo:@{@"images":weakSelf.imageDictionary.allValues}];
                            [weakSelf dismissALLViewController];
                        });
                    }
                }];

            }
            
        }
        
    }

}



-(NSMutableDictionary *)imageDictionary {
    if (!_imageDictionary) {
        _imageDictionary = [NSMutableDictionary dictionary];
    }
    return _imageDictionary;
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = NO;
}


@end
